<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
      <template slot="searchMenu">
        <el-button
          size="small"
          plain
          icon="el-icon-download"
          @click="handleExport"
          >数据导出
        </el-button>
      </template>
      <template slot="page"
        ><div class="page" v-if="data.length > 0">
          <div class="label">总合计：</div>
          <div class="props">{{ total }}</div>
        </div></template
      >
    </avue-crud>
  </basic-container>
</template>

<script>
import { getLevelList, getDictionary } from "@/api/statistics/level";
import $Excel from "avue-plugin-excel";
export default {
  data() {
    return {
      sumColumnList: [],
      arr: [],
      type: "",
      total: 0,
      form: {},
      query: {
        startMonth: this.getRecentMonth_Date(11)[0],
        endMonth: this.getRecentMonth_Date(11)[1],
      },
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      data: [],
    };
  },
  computed: {
    option() {
      return {
        // height: "auto",
        // calcHeight: 30,
        tip: false,
        menu: false,
        searchShow: true,
        searchMenuSpan: 6,
        emptyBtn: false,
        border: true,
        index: false,
        viewBtn: true,
        selection: false,
        // align: "center",
        dialogClickModal: false,
        header: false,
        searchBtnText: "查询",
        emptyBtnText: "重置",
        sumText: "合计",
        showSummary: true,
        sumColumnList: [...this.sumColumnList],
        column: [
          {
            label: "日期区间",
            prop: "createTime",
            type: "monthrange",
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            searchRange: true,
            searchValue:
              this.query.createTime && this.query.createTime.length > 0
                ? this.query.createTime
                : [`${this.query.startMonth}`, `${this.query.endMonth}`],
            searchClearable: false,
            showColumn: false,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              },
            },
            search: true,
          },
          {
            label: "项目类型",
            prop: "type",
            type: "select",
            dicUrl: "/api/fine-system/dict/dictionary?code=wages_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            searchClearable: false,
            showColumn: false,
            searchValue: this.query.type,
            dataType: "string",
            search: true,
            dicFormatter: (res) => {
              return res.data;
            },
          },
          {
            label: `${this.type}统计表（${this.query.startMonth}-${this.query.endMonth}）`,
            align: "center",
            children: [
              {
                label: `项目名称：${this.type}`,
                children: [
                  {
                    label: `会计期间：${this.query.startMonth}-${this.query.endMonth}`,
                    children: [
                      {
                        label: "姓名",
                        prop: "name",
                        align: "center",
                      },
                      {
                        label: "身份证号",
                        prop: "idCard",
                        width: 200,
                        align: "center",
                      },
                      {
                        label: "会计期间",
                        align: "center",
                        children: [],
                      },
                      ...this.arr,
                    ],
                  },
                ],
              },
            ],
          },
        ],
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  mounted() {
    getDictionary().then((res) => {
      this.query.type = res.data.data[0].dictKey;
      this.onLoad(this.page);
    });
  },
  methods: {
    getDatesBetween(start, end) {
      let dates = [];
      let currentDate = new Date(start);
      while (currentDate <= end) {
        let year = currentDate.getFullYear();
        let month = String(currentDate.getMonth() + 1).padStart(2, "0");
        dates.push(`${year}-${month}`);
        currentDate.setMonth(currentDate.getMonth() + 1);
      }
      return dates;
    },
    getRecentMonth_Date(n) {
      const datenow = new Date();
      const dateend =
        datenow.getFullYear().toString() +
        "-" +
        (datenow.getMonth() + 1).toString();
      datenow.setMonth(datenow.getMonth() - n);
      let dyear = datenow.getFullYear();
      let dmonth = datenow.getMonth() + 1;
      dmonth = dmonth < 10 ? 0 + dmonth : dmonth;
      const datestart = dyear.toString() + "-" + dmonth.toString();
      return [datestart, dateend];
    },
    handleExport() {
      let opt = {
        title: `${this.type}统计表（${this.query.startMonth}-${this.query.endMonth}）`,
        column: [
          {
            label: `${this.type}统计表（${this.query.startMonth}-${this.query.endMonth}）`,
            align: "center",
            children: [
              {
                label: `项目名称：${this.type}`,
                children: [
                  {
                    label: `会计期间：${this.query.startMonth}-${this.query.endMonth}`,
                    children: [
                      {
                        label: "姓名",
                        prop: "name",
                        align: "center",
                      },
                      {
                        label: "身份证号",
                        prop: "idCard",
                        align: "center",
                        width: 200,
                      },
                      ...this.arr,
                    ],
                  },
                ],
              },
            ],
          },
        ],
        data: this.data,
      };
      $Excel.excel({
        title: opt.title,
        columns: opt.column,
        data: opt.data,
      });
    },
    setOption() {
      let yearsMonths = this.getDatesBetween(
        new Date(this.query.startMonth),
        new Date(this.query.endMonth)
      );
      let arr = [];
      let sumColumnList = [];
      yearsMonths.forEach((ele) => {
        let obj = {
          label: ele,
          prop: ele,
          align: "center",
        };
        let objs = {
          label: " ",
          name: ele,
          type: "sum",
        };
        sumColumnList.push(objs);
        arr.push(obj);
      });
      sumColumnList[0].label = "合计: ";
      this.sumColumnList = sumColumnList;
      this.arr = arr;
    },
    totalSum(data) {
      let sum = 0;
      sum = Object.values(data).reduce(
        (accumulator, currentValue) => accumulator + currentValue,
        0
      );
      return sum;
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.createTime) {
        params.startMonth = params.createTime[0];
        params.endMonth = params.createTime[1];
        delete params.createTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.setOption();
      this.loading = true;
      getLevelList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      )
        .then((res) => {
          const data = res.data.data;
          this.type = data.type;
          let arrs = this.arr;
          let arr = data.dataList;
          if (arr.length > 0) {
            let obj = {
              name: "合计",
              idCard: "",
            };
            arrs.forEach((ele) => {
              obj[ele] = "";
            });
          }
          this.data = arr;
          //this.data = data.dataList;
          this.total = data.total;
          this.loading = false;
        })
        .catch(() => {
          this.data = [];
          this.loading = false;
        });
    },
  },
};
</script>

<style scoped lang="scss">
.page {
  width: 100%;
  height: 30px;
  text-align: left;
  font-size: 16px;
  display: flex;
  align-items: center;
}
/deep/.avue-crud__pagination {
  padding: 0;
}
</style>
